﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using ECI.CommonLibrary;
using ECI.Controls;
using ECI.CoreLibrary;
using ECI.DynamicData.ElementBuilder;
using ECI.Entities;
using ECI.WebLib.Data;
using ECI.BaseForm;
using ECI.BaseLanguage;

namespace ECI.DynamicData
{
    public class DynamicQuery
    {
        private static ECI.CoreLibrary.CommonLibrary cmn = new ECI.CoreLibrary.CommonLibrary();

        /// <summary>
        /// 创建查询条件区域
        /// </summary>
        /// <param name="pageTable">页面Table</param>
        /// <param name="TableName">配置程序代码</param>
        /// <param name="Rowcells">显示几列</param>
        /// <param name="data">配置程序数据描述</param>
        /// <param name="udfData">控制参数</param>
        public static void GetDynamicSearchTable(ref Table pageTable, string TableName, int Rowcells, EciTable data, UDFData udfData)
        {
            //Authority ECIAuthority = new Authority();
            bool isCreateUQueryControl = udfData.UDF1 == "UQuery";//2010-11-22增加查询条件分离设定

            #region 表头区域
            pageTable.CssClass = "Grid";
            pageTable.Attributes.Add("sql", "auto+page");
            pageTable.CellPadding = 1;
            pageTable.CellSpacing = 0;

            string lblWidth = Math.Ceiling(((1.0 / Rowcells / 3) * 100)).ToString() + "%";
            string txtWidth = Math.Ceiling(((2.0 / Rowcells / 3) * 100)).ToString() + "%";

            int rowCount = data.ListField.Count;
            if (rowCount == 0) pageTable.Visible = false;//如果没有查询条件

            TableHeaderRow th = new TableHeaderRow();
            for (int i = 1; i <= Rowcells; i++)
            {
                TableHeaderCell hcLabel = new TableHeaderCell();
                hcLabel.Style.Add("width", lblWidth);

                TableHeaderCell hcText = new TableHeaderCell();
                hcText.Style.Add("width", txtWidth);

                th.Cells.Add(hcLabel);
                th.Cells.Add(hcText);
            }

            pageTable.Rows.Add(th);

            #endregion

            #region 设置默认获得焦点
            if (rowCount > 0)
            {
                string focusId = "txt" + data.ListField[0].Name;
                UIControlExtend.ECIFocus(focusId);
                //TODO:可能未来需要配置默认 获焦控件
            }
            #endregion

            #region 查询区域
            int columnIndex = 100;
            TableRow tableRow = new TableRow();

            string queryShowCommon = "", f = "0";

            string type = "Query";
            IElement element = null;
            ElementParameter parameter = null;

            for (int i = 0; i < rowCount; i++)
            {
                #region
                EciField field = data.ListField[i];
                if (columnIndex >= Rowcells)
                {
                    tableRow = new TableRow();
                    tableRow.Attributes.Add("QueryCommon", field.QueryShowCommon.ToString());
                    pageTable.Rows.Add(tableRow);
                    columnIndex = 0;
                }
                if (queryShowCommon == "1")
                    f = "1";

                if (queryShowCommon != field.QueryShowCommon.ToString() && queryShowCommon != "" && field.QueryShowCommon.ToString() != "")
                {
                    if (tableRow.Cells.Count != 0)
                    {
                        for (int k = tableRow.Cells.Count; k < Rowcells * 2; k++)
                        {
                            TableCell emptyCell = new TableCell();
                            emptyCell.Text = "&nbsp;";
                            tableRow.Cells.Add(emptyCell);
                        }
                    }
                    //强制换行处理
                    tableRow = new TableRow();
                    tableRow.Attributes.Add("QueryCommon", field.QueryShowCommon.ToString());
                    pageTable.Rows.Add(tableRow);
                    columnIndex = 0;
                }
                columnIndex++;

                #region 创建每一个查询元素对象
                element = null;
                parameter = new ElementParameter();
                parameter.TableRow = tableRow;
                parameter.Field = field;
                parameter.DataRow = null;//数据行
                parameter.CellWidth = txtWidth;
                parameter.type = type;
                parameter.EditMode = "";
                parameter.HideCell = null;

                string dataType = data.ListField[i].DictionaryType.ToString().ToUpper();//类型
                switch (dataType)
                {
                    case "INPUT":
                    case "INPUT_NUMBER":
                    case "MEMO":
                    case "INPUT_INT": AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon); element = new TInput(); element.Create(parameter); break;
                    case "CHOOSE": AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon); element = new TChoose(); element.Create(parameter); break;
                    case "DATE":
                        #region 日期类型 考虑日期区段查询
                        if (field.SqlAttribute.ToLower().Contains("startend"))
                        {

                            if (columnIndex == Rowcells)
                            {
                                AddLableCell(tableRow, "", field.QueryShowCommon);
                                AddTextCell(tableRow, "", field.QueryShowCommon);

                                tableRow = new TableRow();
                                pageTable.Rows.Add(tableRow);
                                tableRow.Attributes.Add("QueryCommon", field.QueryShowCommon.ToString());
                                AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon);
                                CreateDateForQuery(tableRow, field, txtWidth, lblWidth, type, "");
                                columnIndex = 2;
                            }
                            else
                            {
                                AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon);
                                CreateDateForQuery(tableRow, field, txtWidth, lblWidth, type, "");
                                columnIndex++;
                            }
                        }
                        else
                        {
                            AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon);
                            element = new TDate(); element.Create(parameter);
                        }

                        break;
                        #endregion
                    case "CHECK": AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon); element = new TCheckBox(); parameter.query = "select"; element.Create(parameter); break;
                    case "DROPDOWNLIST": AddLableCell(tableRow, field.MainAlias, field.QueryShowCommon); element = new TDropdownList(); parameter.query = "select"; element.Create(parameter); break;
                }

                //设定查询默认条件
                if (element != null)
                {
                    element.QueryDefault();
                }
                #endregion

                #region 最后一行追加空格
                if (i == rowCount - 1)
                {
                    for (int k = tableRow.Cells.Count; k < Rowcells * 2; k++)
                    {
                        TableCell emptyCell = new TableCell();
                        emptyCell.Text = "&nbsp;";
                        tableRow.Cells.Add(emptyCell);
                    }
                }
                #endregion

                queryShowCommon = field.QueryShowCommon.ToString();

                #endregion
            }
            #endregion

            #region 功能按钮区域

            if (data.ListField.Count > 0)
            {
                TableRow footerRow = new TableRow();
                TableCell footerCell = new TableCell();
                footerCell.ColumnSpan = Rowcells * 2;
                footerCell.HorizontalAlign = HorizontalAlign.Center;
                footerRow.Cells.Add(footerCell);
                footerRow.Attributes.Add("QueryCommon", f);
                th.Attributes.Add("QueryCommon", f);
                pageTable.Rows.Add(footerRow);

                Button btnQuery = new Button();
                btnQuery.Text = Lang.A00066.Read();

                btnQuery.AccessKey = "q";
                btnQuery.CssClass = "btn";
                btnQuery.ID = "btnSearch";
                footerCell.Controls.Add(btnQuery);
                HtmlInputButton btnReset = new HtmlInputButton();

                string ascxId = pageTable.Parent.Parent.ClientID;
                string pnlId = pageTable.Parent.ClientID;

                btnReset.Value = Lang.A00067.Read();//重 置(R)
                btnReset.Attributes.Add("AccessKey", "r");
                btnReset.Attributes.Add("class", "btn");
                btnReset.ID = "btnReset";
                footerCell.Controls.Add(btnReset);

                if (isCreateUQueryControl)
                {
                    btnReset.Attributes.Add("onclick", "ResetDOM('" + ascxId + "_TbQuery');");
                }
                else
                {
                    btnReset.Attributes.Add("onclick", "ResetDOM('tbQuery');");
                }

                if (SystemInfo.MultiLanguageMode)
                {
                    btnQuery.Text = Lang.A00005.Read();
                    btnReset.Value = Lang.A00006.Read();
                }

                if (ECI.CoreLibrary.Config.ConfigReader.GetConfig("PL_DEBUG_MODE") == "Y")
                {
                    Literal lt = new Literal();
                    lt.Text = "<span id ='__PageCode' style='display:none'><b>" + data.Code + "</b></span>";
                    footerCell.Controls.Add(lt);
                    string script = "HideShowDOM('__PageCode');";
                    footerRow.Attributes.Add("ondblclick", script);
                }

                #region 如果查询条件是控件弹出式的情况 增加关闭按钮
                if (isCreateUQueryControl)
                {
                    HtmlInputButton btnClose = new HtmlInputButton();

                    btnClose.Value = Lang.A00068.Read();//关 闭(X)
                    btnClose.Attributes.Add("AccessKey", "x");
                    btnClose.Attributes.Add("class", "btn");
                    btnClose.ID = "btnClose";

                    btnClose.Attributes.Add("onclick", "DOMMiddle('div" + pnlId + "',false,'');");
                    footerCell.Controls.Add(btnClose);

                    btnQuery.Click += new EventHandler(btnQuery_Click);

                    if (SystemInfo.MultiLanguageMode)
                    {
                        btnClose.Value = Lang.A00034.Read() + "(X)";
                    }
                }
                #endregion
            }
            #endregion
        }

        /// <summary>
        /// 查询条件控件的查询事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void btnQuery_Click(object sender, EventArgs e)
        {
            IQuery query = PageHelper.CurrentPage as IQuery;
            query.Query();
        }

        public static void GetDynamicSearchTable(ref Table pageTable, string TableName, int Rowcells, EciTable data)
        {
            GetDynamicSearchTable(ref pageTable, TableName, Rowcells, data, new UDFData());
        }

        public static void GetDynamicEditTable(Table parentTable, EciTable myEciTable, string key, string editMode)
        {
            //创建表头
            EditPageResult pageResult = GetDynamicEditTableHeader(parentTable, myEciTable, key, editMode);
            List<EciTableGroup> listGroupInfo = myEciTable.ListGroup;

            foreach (EciTableGroup groupInfo in listGroupInfo)
            {
                #region 获取显示列数
                int displayCount = 2;
                if (groupInfo.GroupCode == "")
                {
                    if (myEciTable.ColumnCount.HasValue)
                    {
                        displayCount = Convert.ToInt32(myEciTable.ColumnCount.Value);
                    }
                }
                else
                {

                    displayCount = groupInfo.ColumnCount.ToIntIgnoreError();
                    if (displayCount == 0)
                    {
                        displayCount = Convert.ToInt32(myEciTable.ColumnCount.Value);
                    }
                }
                #endregion

                //创建没一个分组
                GetDynamicEditTableEachGroup(pageResult, parentTable, groupInfo, displayCount, myEciTable, key, editMode);
            }
        }

        /// <summary>
        /// 创建表头
        /// </summary>
        /// <param name="pageTable">页面Table</param>
        /// <param name="myEciTable">配置程序数据描述</param>
        /// <param name="key">KEY值</param>
        /// <param name="editMode">编辑模式</param>
        /// <returns></returns>
        private static EditPageResult GetDynamicEditTableHeader(Table pageTable, EciTable myEciTable, string key, string editMode)
        {
            EditPageResult editPageResult = new EditPageResult();

            Table tbHeader = new Table();
            tbHeader.CellPadding = 0;
            tbHeader.CellSpacing = 0;
            tbHeader.Style.Add("width", "100%");

            int editFieldCount = myEciTable.ListEdit.Count;//编辑控件的数量
            TableRow headerRow = new TableRow();
            TableCell headerCell = new TableCell();
            headerRow.Cells.Add(headerCell);
            tbHeader.Rows.Add(headerRow);
            headerCell.HorizontalAlign = HorizontalAlign.Center;

            #region 设置程序标题和页面标题
            string mainAlias = myEciTable.FmainAlias;

            if (myEciTable.EditTitle != "")
            {
                mainAlias = myEciTable.EditTitle;
            }

            if (myEciTable.Code == "ECI_DATACODE")
            {
                string groupName = PageHelper.Request("GROUP_NAME");
                EciDataGroup dataGroup = new EciDataGroup(EciDataGroupEnum.GroupCode);
                dataGroup.GroupCode = groupName;
                dataGroup = dataGroup.FetchEntity();
                mainAlias = dataGroup.GroupName;
            }

            string title = mainAlias;
            if (myEciTable.Title == "")
            {
                string titleEx = "-[" + Lang.A00013.Read() + "]";//新增

                if (key != "" && editMode.ToLower() != "copy")
                {
                    titleEx = "-[" + Lang.A00012.Read() + "]";//编辑
                }
                title += titleEx;
            }
            else
            {
                title = myEciTable.Title;
            }

            Label lblTitle = new Label();
            lblTitle.ID = "lblTitle";

            lblTitle.Text = SQLParamConvert.Convert(title);
            PageHelper.CurrentPage.Title = title;
            lblTitle.Font.Bold = true;
            headerCell.Controls.Add(lblTitle);
            lblTitle.CssClass = "PageTitle";
            headerCell.Height = 25;
            headerCell.HorizontalAlign = HorizontalAlign.Center;

            if (ECI.CoreLibrary.Config.ConfigReader.GetConfig("PL_DEBUG_MODE") == "Y")
            {
                Literal lt = new Literal();
                lt.Text = "<span id ='__PageCode' style='display:none'><b>" + myEciTable.Code + "</b></span>";
                headerCell.Controls.Add(lt);
                string script = "HideShowDOM('__PageCode');";
                headerRow.Attributes.Add("ondblclick", script);
                lblTitle.Attributes.Add("ondblclick", script);
            }

            #endregion

            #region 创建隐藏域行
            TableRow HideRow = new TableRow();
            TableCell HideCell = new TableCell();
            HideCell.HorizontalAlign = HorizontalAlign.Center;
            HideRow.Cells.Add(HideCell);
            tbHeader.Rows.Add(HideRow);
            HideRow.Style.Add("display", "none");

            editPageResult.HideCell = HideCell;
            AddTable(myEciTable, pageTable, tbHeader, null);
            #endregion

            #region 获取基本数据源
            if (!string.IsNullOrEmpty(key))
            {
                DataTable dataTable = null;
                string sql = ECI.DynamicData.DataCache.EditSQL.Get(myEciTable, key);
                dataTable = DBHelper.GetDataTable(sql);

                if (PlatformInfo.DevelopMode)
                {
                    LOG.Write(sql, "获取基本数据源");
                }

                if (!cmn.CheckEOF(dataTable))
                {
                    throw new Exception(Lang.A00069.Read());//程序异常:没有查询到数据
                }
                editPageResult.DataEditRow = dataTable.Rows[0];
            }
            #endregion

            #region 创建其他数据源
            editPageResult.DataSource = new DataSet();

            foreach (EciTableDataSource tableDataSource in myEciTable.ListDataSource)
            {
                string sql = tableDataSource.Sql;
                //替换参数 动态解析 sql 语句中的{A},{B} 部分
                List<string> listParam = DynamicParam.GetParam(sql);
                foreach (string item in listParam)
                {
                    if (PageHelper.Request(item) == "")
                    {
                        //throw new Exception(Lang.A00070.Read() + tableDataSource.Name + Lang.A00071.Read() + item);//没有传入数据源
                    }
                    sql = sql.Replace("{" + item + "}", PageHelper.Request(item));
                }

                //替换参数 动态解析 sql语句中的## 部分
                //sql = sql.Replace("#USER_ID#", UserInfo.UserId);
                //sql = sql.Replace("#DEPT_ID#", UserInfo.OperSide);
                sql = SQLParamConvert.Convert(sql);//转化SQL参数替换

                DataTable data = null;
                try
                {
                    data = DBHelper.GetDataTable(sql);
                    data.TableName = tableDataSource.Name;
                    editPageResult.DataSource.Merge(data);
                }
                catch
                {
                    throw new Exception(Lang.A00072.Read() + tableDataSource.Name + Lang.A00228.Read() + sql);//获取数据源
                }
            }

            #endregion

            return editPageResult;
        }

        private static void AddTable(EciTable myEciTable, Table parentTable, Table table, EciTableGroup groupInfo)
        {

            TableRow tableRow = new TableRow();
            TableCell tableCell = new TableCell();

            if (groupInfo != null && groupInfo.GroupCode != "")
            {
                tableRow.Cells.Add(tableCell);
                SetGroupTitle(tableCell, groupInfo);
                parentTable.Rows.Add(tableRow);
            }

            tableRow = new TableRow();
            tableCell = new TableCell();
            tableRow.Cells.Add(tableCell);
            tableCell.Controls.Add(table);
            parentTable.Rows.Add(tableRow);

            if (groupInfo != null && groupInfo.GroupCode != "")
            {
                UIPart.UIPart.LoadControl(myEciTable, groupInfo.GroupCode, parentTable, table);
            }
        }

        private static void SetGroupTitle(TableCell cell, EciTableGroup groupInfo)
        {
            if (groupInfo.DisplayType.StartsWith("LINK"))
            {
                Literal ltTitle = new Literal();
                string tableName = "tbEditGroup_" + groupInfo.GroupCode;
                ltTitle.Text = string.Format("<a  href=\"javascript:HideShowDOM('{0}');" + groupInfo.Udf1 + "\" >" + groupInfo.Title + "</a>", tableName);
                cell.Controls.Add(ltTitle);
                if (groupInfo.TitleCustomerHtml.Length > 0)
                {
                    Literal ltTitleHTML = new Literal();
                    ltTitleHTML.Text = "&nbsp;" + groupInfo.TitleCustomerHtml;
                    cell.Controls.Add(ltTitleHTML);
                }
            }
            else
            {
                cell.Text = groupInfo.Title;
            }
        }

        /// <summary>
        /// 获取编辑页面
        /// </summary>
        /// <param name="pageTable">页面Table</param>
        /// <param name="TableName">数据字典-中文名称</param>
        /// <param name="Rowcells">显示列数</param>
        /// <param name="data">数据字典</param>
        /// <param name="key">编辑主键KEY</param>
        /// <param name="editMode">编辑模式</param>
        private static void GetDynamicEditTableEachGroup(EditPageResult editPageResult, Table ParentTable, EciTableGroup groupInfo, int displayCount, EciTable myEciTable, string key, string editMode)
        {
            if (myEciTable.ListEdit.Count < 0)
                return;

            DataRow dataRow = editPageResult.DataEditRow;

            Table pageTable = new Table();
            List<CellRowSpanInfo> listRowSpanInfo = new List<CellRowSpanInfo>();

            pageTable.CssClass = "Grid";
            pageTable.CellPadding = 0;
            pageTable.CellSpacing = 0;

            pageTable.ID = "tbEditGroup_" + groupInfo.GroupCode;

            if (groupInfo.DisplayType == "LINK_HIDE")
            {
                pageTable.Style.Add("display", "none");
            }

            string[] array = null;
            if (myEciTable.GridLayout.ToMyString().Trim().Length > 0)
            {
                array = myEciTable.GridLayout.Split('-');
                if (displayCount * 2 != array.Length)
                {
                    throw new Exception(Lang.A00073.Read());//程序-表格布局配置-不正确
                }
            }

            int editFieldCount = myEciTable.ListEdit.Count;//编辑控件的数量

            #region 增加ECI_FIELD_EXTEND

            //DataRow dataRowExtend = null;

            //if (myEciTable.ListFieldExtend.Count > 0)
            //{
            //    DataTable dataTable = null;
            //    string sql = GetEditExtendSQL(myEciTable);
            //    dataTable = DBHelper.GetDataTable(sql);
            //    if (!cmn.CheckEOF(dataTable)) throw new Exception("程序异常:没有查询到数据 ");
            //    dataRowExtend = dataTable.Rows[0];
            //}

            //TableRow extendTableRow = new TableRow();

            //int extendIndex = 100;

            //foreach (EciFieldExtend filedExtend in myEciTable.ListFieldExtend)
            //{

            //    if (extendIndex >= displayCount)
            //    {
            //        extendTableRow = new TableRow();
            //        pageTable.Rows.Add(extendTableRow);
            //        extendIndex = 0;
            //    }

            //    extendIndex++;


            //    TableCell tableCell = new TableCell();
            //    tableCell.Attributes.Add("style", "white-space:nowrap");
            //    tableCell.Attributes.Add("class", "lbl");

            //    Label label = new Label();
            //    label.Text = filedExtend.MainAlias;//字段中文名
            //    tableCell.Controls.Add(label);
            //    extendTableRow.Cells.Add(tableCell);


            //    tableCell = new TableCell();
            //    tableCell.Attributes.Add("style", "white-space:nowrap");
            //    tableCell.Style["width"] = txtWidth;

            //    TextBox txtBox = new TextBox();
            //    txtBox.Style["width"] = "85%";
            //    if (dataRowExtend != null)
            //    {
            //        txtBox.Text = dataRowExtend[filedExtend.Name].ToString();
            //    }

            //    string contolId = "txt" + filedExtend.Name + "Extend";
            //    txtBox.ID = contolId;
            //    txtBox.ReadOnly = true;
            //    txtBox.BackColor = System.Drawing.Color.Gainsboro;
            //    tableCell.Controls.Add(txtBox);
            //    extendTableRow.Cells.Add(tableCell);
            //}


            //#region 最后一行追加

            //for (int k = extendTableRow.Cells.Count; k < displayCount * 2; k++)
            //{
            //    TableCell emptyCell = new TableCell();
            //    emptyCell.Text = "&nbsp;";
            //    extendTableRow.Cells.Add(emptyCell);
            //}

            //#endregion


            #endregion

            if (editFieldCount > 0)
            {
                string focusId = "txt" + myEciTable.ListEdit[0].Name;
                if (myEciTable.ListEdit[0].DictionaryType == "DROPDOWNLIST") focusId = "cbo" + myEciTable.ListEdit[0].Name;
                UIControlExtend.ECIFocus(focusId);
            }

            //计算文本和编辑框的显示百分比
            string lblWidth = Math.Ceiling(((1.0 / displayCount / 3) * 100)).ToString() + "%";
            string txtWidth = Math.Ceiling(((2.0 / displayCount / 3) * 100)).ToString() + "%";

            int columnIndex = 0;
            TableHeaderRow th = new TableHeaderRow();

            for (int i = 1; i <= displayCount; i++)
            {
                TableHeaderCell hcLabel = new TableHeaderCell();
                TableHeaderCell hcText = new TableHeaderCell();
                if (myEciTable.GridLayout.ToMyString().Trim().Length > 0)
                {
                    hcLabel.Style.Add("width", array[columnIndex++]);
                    hcText.Style.Add("width", array[columnIndex++]);
                }
                else
                {
                    hcLabel.Style.Add("width", lblWidth);
                    hcText.Style.Add("width", txtWidth);
                }

                th.Cells.Add(hcLabel);
                th.Cells.Add(hcText);
            }

            pageTable.Rows.Add(th);


            #region 每一个配置字段


            bool LastFieldWrap = false;
            TableRow tableRow = new TableRow();
            TableCell defaultCell = new TableCell();
            defaultCell.ColumnSpan = 100;
            tableRow.Cells.Add(defaultCell);

            for (int i = 0; i < editFieldCount; i++)
            {
                bool NeedCreateControl = true;

                EciField field = myEciTable.ListEdit[i];//当前需要创建的编辑字段
                if (field.GroupCode.ToUpper() != groupInfo.GroupCode.ToUpper()) continue;//如果不是在当前分组 则不加入 2010-06-25

                string fieldDictionaryType = field.DictionaryType.ToString().ToUpper();//类型

                string myHorizontalAlign = field.HorizontalAlignLabel.ToMyString();
                string myVerticalAlign = field.VerticalAlignLabel.ToMyString();

                #region 获取ROWSPAN 和COLSPAN
                int fieldColumnSpan = 1;
                if (field.Colspan.HasValue)
                {
                    if (field.Colspan.Value > 1)
                    {
                        fieldColumnSpan = Convert.ToInt32(field.Colspan);
                    }
                }

                int fieldRowSpan = 1;
                if (field.Rowspan.HasValue)
                {
                    if (field.Rowspan.Value > 1)
                    {
                        fieldRowSpan = Convert.ToInt32(field.Rowspan);
                    }
                }
                #endregion

                #region 准备TableRow  如果当前行的单元格应该满了 则要增加新的单元格
                if (GetTableRowColumnCount(tableRow) >= displayCount * 2)
                {
                    tableRow = new TableRow();
                    pageTable.Rows.Add(tableRow);
                }
                #endregion


                //记录ROWSPAN情况
                if (fieldRowSpan > 1)
                {
                    CellRowSpanInfo spanInfo = new CellRowSpanInfo();
                    spanInfo.ColSpan = fieldColumnSpan;
                    spanInfo.RowSpan = fieldRowSpan;
                    spanInfo.RowIndex = pageTable.Rows.Count;
                    listRowSpanInfo.Add(spanInfo);
                }


                //注意：当前创建的控件 将加入在 tableRow行

                if (fieldDictionaryType == "EMPTY")
                {
                    #region 占位符
                    TableCell tableCell = new TableCell();
                    tableCell.VerticalAlign = VerticalAlign.Top;
                    tableCell.Attributes.Add("style", "white-space:nowrap");
                    if (field.Css.Trim().Length == 0)
                    {
                        tableCell.Attributes.Add("class", "lbl");
                    }
                    else
                    {
                        tableCell.Attributes.Add("class", field.Css);
                    }
                    Label labelNull = new Label();
                    labelNull.Text = "&nbsp;";

                    tableCell.Controls.Add(labelNull);
                    tableRow.Cells.Add(tableCell);
                    tableCell.ColumnSpan = fieldColumnSpan;

                    NeedCreateControl = false;
                    #endregion
                }
                else
                {
                    if (fieldDictionaryType == "LABEL")
                    {
                        //2010-06-25 增加LABEL的显示
                        #region 创建文字描述单元格
                        TableCell tableCell = new TableCell();
                        tableCell.VerticalAlign = VerticalAlign.Top;
                        tableCell.Attributes.Add("style", "white-space:nowrap");
                        //tableCell.Attributes.Add("class", "lbl"); 如果放此Class 会影响下面的 HorizontalAlign 设置显示效果
                        tableCell.ColumnSpan = fieldColumnSpan;
                        tableCell.RowSpan = fieldRowSpan;
                        Label label = new Label();
                        label.Text = field.MainAlias;


                        #region 设置CELL的居中方式
                        if (myHorizontalAlign == "1")
                        {
                            tableCell.HorizontalAlign = HorizontalAlign.Left;
                        }
                        if (myHorizontalAlign == "2")
                        {
                            tableCell.HorizontalAlign = HorizontalAlign.Center;
                        }
                        if (myHorizontalAlign == "3")
                        {
                            tableCell.HorizontalAlign = HorizontalAlign.Right;
                        }

                        if (myHorizontalAlign == "1")
                        {
                            tableCell.VerticalAlign = VerticalAlign.Top;
                        }
                        if (myHorizontalAlign == "2")
                        {
                            tableCell.VerticalAlign = VerticalAlign.Middle;
                        }
                        if (myHorizontalAlign == "3")
                        {
                            tableCell.VerticalAlign = VerticalAlign.Bottom;
                        }
                        #endregion

                        tableCell.Controls.Add(label);
                        tableRow.Cells.Add(tableCell);

                        NeedCreateControl = false;

                        #endregion
                    }
                    else
                    {
                        #region 创建标题
                        //当前要创建的对象 当前行后面的CELL是否能容纳下
                        //2010-06-29  增加控制 如果前一个控件是自动换行的情况下那么要强行换行
                        if (LastFieldWrap)
                        {
                            FillTableRow(tableRow, displayCount, listRowSpanInfo);
                            tableRow = new TableRow();
                            pageTable.Rows.Add(tableRow);
                        }
                        else
                        {
                            #region
                            int currentUseCells = GetTableRowColumnCount(tableRow);
                            //2010-06-25  增加了ROWSPAN 控制
                            int hasResumeByPreRow = GetResumeByPreRow(pageTable.Rows.Count, listRowSpanInfo);
                            int labelPosition = 1;
                            if (field.EditHideLabel.ToMyString() == "1") labelPosition = 0;

                            if (currentUseCells + hasResumeByPreRow + labelPosition + fieldColumnSpan > displayCount * 2)
                            {
                                FillTableRow(tableRow, displayCount, listRowSpanInfo);
                                tableRow = new TableRow();
                                pageTable.Rows.Add(tableRow);
                            }
                            #endregion
                        }

                        //2010-06-25 增加控制 是否显示LABEL
                        if (field.EditHideLabel.ToMyString() == "0")
                        {
                            #region 创建文字描述单元格
                            TableCell tableCell = new TableCell();
                            tableCell.VerticalAlign = VerticalAlign.Top;
                            tableCell.Attributes.Add("style", "white-space:nowrap");
                            if (myHorizontalAlign == "" || myHorizontalAlign == "0")
                            {
                                tableCell.Attributes.Add("class", "lbl");
                            }

                            #region 设置CELL的居中方式
                            if (myHorizontalAlign == "1")
                            {
                                tableCell.HorizontalAlign = HorizontalAlign.Left;
                            }
                            if (myHorizontalAlign == "2")
                            {
                                tableCell.HorizontalAlign = HorizontalAlign.Center;
                            }
                            if (myHorizontalAlign == "3")
                            {
                                tableCell.HorizontalAlign = HorizontalAlign.Right;
                            }

                            if (myHorizontalAlign == "1")
                            {
                                tableCell.VerticalAlign = VerticalAlign.Top;
                            }
                            if (myHorizontalAlign == "2")
                            {
                                tableCell.VerticalAlign = VerticalAlign.Middle;
                            }
                            if (myHorizontalAlign == "3")
                            {
                                tableCell.VerticalAlign = VerticalAlign.Bottom;
                            }
                            #endregion

                            #endregion

                            #region 创建必输项 Label 提示 同时将 notnull属性 增加到PageTable的notnull属性中 便于保存时调用 检查
                            if (field.NullableKey.ToMyString() == "0")
                            {
                                string contolId = "txt" + field.Name;
                                Label lblNotNull = new Label();
                                lblNotNull.ForeColor = System.Drawing.Color.Red;
                                lblNotNull.Text = "*";
                                tableCell.Controls.Add(lblNotNull);
                                tableCell.Style["width"] = lblWidth;

                                string attribute = ParentTable.Attributes["notnull"];
                                if (string.IsNullOrEmpty(attribute)) ParentTable.Attributes["notnull"] = contolId;
                                else ParentTable.Attributes["notnull"] = attribute + "," + contolId;
                            }
                            #endregion

                            #region 创建字段文字描述Label
                            Label label = new Label();
                            label.Text = field.MainAlias;//显示查询字段中文名

                            if (label.Text.ToUpper() == "NULL")
                            {
                                label.Text = "";
                            }

                            tableCell.Controls.Add(label);
                            //2010-07-14 增加Hidden属性
                            if (!EditHideForSystemField(field) && field.Hidden == "N")
                            {
                                if (field.AfterElement == "")
                                {
                                    tableRow.Cells.Add(tableCell);
                                }
                            }
                            #endregion
                        }

                        #endregion
                    }


                    if (NeedCreateControl)
                    {
                        #region 根据该字段配置的数据字典类型 创建对应的控件

                        string name = field.Name.ToString().ToUpper();//类型

                        string type = "Edit";

                        IElement element = null;
                        ElementParameter param = new ElementParameter();
                        param.TableRow = tableRow;//当前的行
                        param.Field = field;//数据字段
                        param.DataRow = dataRow;//编辑数据
                        param.DataSource = editPageResult.DataSource;//其他数据源数据
                        param.CellWidth = txtWidth;//编辑框宽度
                        param.type = type;
                        param.EditMode = editMode;
                        param.HideCell = editPageResult.HideCell;
                        param.query = type;
                        param.EciTable = myEciTable;


                        element = ElementFactory.Create(fieldDictionaryType);
                        element.Create(param);

                        element.Locked();
                        element.Default();
                        element.DataKeep();
                        element.CreateEditTip();//2010-09-02 21:07

                        if (param.type == "Edit" && param.Field.SystemData.ToMyString() != "")
                        {
                            element.SystemField();
                        }

                        if (myEciTable.Condition.ToLower() == field.Name.ToLower())
                        {
                            element.Cascade();
                        }

                        #endregion
                    }


                    LastFieldWrap = field.Wrap == "Y";
                }

                #region 最后一行追加
                if (i == editFieldCount - 1)
                {
                    FillTableRow(tableRow, displayCount, listRowSpanInfo);
                }
                #endregion
            }

            #endregion

            if (pageTable.Rows.Count > 1)
            {
                AddTable(myEciTable, ParentTable, pageTable, groupInfo);
            }
        }

        private static void FillTableRow(TableRow tableRow, int displayCount, List<CellRowSpanInfo> spanInfo)
        {
            int currentCells = GetTableRowColumnCount(tableRow);
            //获取被前面行占用的列数
            Table table = (Table)tableRow.Parent;
            int hasResumeByPreRow = GetResumeByPreRow(table.Rows.Count, spanInfo);
            //for (int k = currentCells+hasResumeByPreRow; k < displayCount * 2; k++)
            //{
            //    TableCell emptyCell = new TableCell();
            //    emptyCell.Text = "&nbsp;";
            //    tableRow.Cells.Add(emptyCell);
            //}
            int colSpan = displayCount * 2 - currentCells + hasResumeByPreRow;
            if (colSpan > 0)
            {
                TableCell emptyCell = new TableCell();
                emptyCell.ColumnSpan = colSpan;
                emptyCell.Text = "&nbsp;";
                tableRow.Cells.Add(emptyCell);
            }
        }

        private static int GetResumeByPreRow(int currentRow, List<CellRowSpanInfo> spanInfo)
        {
            int result = 0;
            foreach (CellRowSpanInfo item in spanInfo)
            {
                if (item.RowIndex + item.RowSpan >= currentRow && item.RowIndex < currentRow)
                {
                    result += item.ColSpan;
                }
            }
            return result;
        }

        public static void GetDynamicEditTableBatch(Table pageTable, string TableName, EciTable data, string editMode)
        {
            string lblWidth = "30%";
            string txtWidth = "70%";

            pageTable.CssClass = "Grid";
            pageTable.CellPadding = 1;
            pageTable.CellSpacing = 0;

            int rowCount = data.ListBatchEdit.Count;
            TableRow headerRow = new TableRow();
            TableCell headerCell = new TableCell();
            headerCell.Text = TableName + "-[批量修改]";
            headerCell.ColumnSpan = 2;
            headerCell.HorizontalAlign = HorizontalAlign.Center;
            headerRow.Cells.Add(headerCell);
            pageTable.Rows.Add(headerRow);

            #region 批量修改字段
            for (int i = 0; i < rowCount; i++)
            {
                TableRow tableRow = new TableRow();
                EciField field = data.ListBatchEdit[i];

                TableCell tableCell = new TableCell();
                tableCell.VerticalAlign = VerticalAlign.Top;
                tableCell.Attributes.Add("style", "white-space:nowrap");
                tableCell.Attributes.Add("class", "lbl");

                if (field.NullableKey.ToMyString() == "0")
                {
                    string contolId = field.Name;
                    Label lblNotNull = new Label();
                    lblNotNull.ForeColor = System.Drawing.Color.Red;
                    lblNotNull.Text = "*";
                    tableCell.Controls.Add(lblNotNull);
                    tableCell.Style["width"] = lblWidth;

                    string attribute = pageTable.Attributes["notnull"];
                    if (string.IsNullOrEmpty(attribute)) pageTable.Attributes["notnull"] = contolId;
                    else
                    {
                        if (!attribute.Contains(contolId))
                        {
                            pageTable.Attributes["notnull"] = attribute + "," + contolId;
                        }
                    }
                }

                CheckBox chk = new CheckBox();
                chk.TextAlign = TextAlign.Left;
                chk.Text = field.MainAlias;//显示查询字段中文名
                tableCell.Controls.Add(chk);
                tableRow.Cells.Add(tableCell);
                chk.ID = "chk" + field.Name;
                chk.Attributes.Add("mainalias", field.MainAlias);

                string updateField = pageTable.Attributes["updateField"];
                if (string.IsNullOrEmpty(updateField)) pageTable.Attributes["updateField"] = chk.ID;
                else
                {
                    if (!updateField.Contains(chk.ID))
                    {
                        pageTable.Attributes["updateField"] = updateField + "," + chk.ID;
                    }
                }

                string dataType = field.DictionaryType.ToString().ToUpper();//类型
                string name = field.Name.ToString().ToUpper();//类型

                string type = "BathUpdate";

                IElement element = null;
                ElementParameter parameter = new ElementParameter();
                parameter.TableRow = tableRow;
                parameter.Field = field;
                parameter.DataRow = null;//数据行
                parameter.CellWidth = txtWidth;
                parameter.type = type;
                parameter.EditMode = editMode;
                parameter.HideCell = null;

                switch (dataType)
                {
                    case "INPUT":
                    case "INPUT_NUMBER":
                    case "INPUT_INT": element = new TInput(); element.Create(parameter); break;
                    case "CHOOSE": element = new TChoose(); element.Create(parameter); break;
                    case "MEMO": element = new TMemo(); element.Create(parameter); break;
                    case "DATE":
                    case "DATE_START":
                    case "DATE_END": element = new TDate(); element.Create(parameter); break;
                    case "CHECK": element = new TCheckBox(); parameter.query = "edit"; element.Create(parameter); break;
                    case "DROPDOWNLIST": element = new TDropdownList(); parameter.query = "edit"; element.Create(parameter); break;
                    case "RADIONGROUP": CreateRadionButtonList(tableRow, field, null, "edit", txtWidth, type, editMode); break;
                }

                pageTable.Rows.Add(tableRow);
            }
            #endregion
        }

        private static void AddLableCell(TableRow tableRow, string text)
        {
            TableCell tableCell = new TableCell();
            tableCell.VerticalAlign = VerticalAlign.Top;
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Attributes.Add("class", "lbl");
            Label label = new Label();
            label.Text = text;
            tableCell.Controls.Add(label);
            tableRow.Cells.Add(tableCell);
        }

        private static void AddLableCell(TableRow tableRow, string text, double? cellAttribute)
        {
            TableCell tableCell = new TableCell();
            tableCell.Attributes.Add("QueryCommon", cellAttribute.ToString());
            tableCell.VerticalAlign = VerticalAlign.Top;
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Attributes.Add("class", "lbl");
            Label label = new Label();
            label.Text = text;
            tableCell.Controls.Add(label);
            tableRow.Cells.Add(tableCell);
        }

        private static void AddTextCell(TableRow tableRow, string text, double? cellAttribute)
        {
            TableCell tableCell = new TableCell();
            tableCell.Attributes.Add("QueryCommon", cellAttribute.ToString());
            tableCell.VerticalAlign = VerticalAlign.Top;
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Attributes.Add("class", "txt");
            Label label = new Label();
            label.Text = text;
            tableCell.Controls.Add(label);
            tableRow.Cells.Add(tableCell);
        }

        private static void AddTextCell(TableRow tableRow, string text)
        {
            TableCell tableCell = new TableCell();
            tableCell.VerticalAlign = VerticalAlign.Top;
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Attributes.Add("class", "txt");
            Label label = new Label();
            label.Text = text;
            tableCell.Controls.Add(label);
            tableRow.Cells.Add(tableCell);
        }

        private static int GetTableRowColumnCount(TableRow tableRow)
        {
            int count = 0;
            foreach (TableCell cell in tableRow.Cells)
            {
                count += cell.ColumnSpan == 0 ? 1 : cell.ColumnSpan;
            }

            return count;
        }

        public static string InsertDynamicData(Table pageTable, EciTable data)
        {
            object ts = (PageHelper.CurrentPage as IRecord).GetTransaction();
            if (data.PrimaryKey == null) throw new Exception(Lang.A00055.Read());//没有配置主键

            List<object> listParam = new List<object>();
            //唯一键检查
            foreach (EciField item in data.ListEdit)
            {

                if (item.PhysicalType == "CLOB")
                {
                    IElement element = ElementFactory.Create(item.DictionaryType);
                    ElementParameter param = new ElementParameter();
                    param.Table = pageTable;
                    param.Field = item;
                    param.editMode = DynamicEditMode.Insert;
                    element.Init(param);
                    string paramValue = element.GetRealValue();
                    listParam.Add(DBHelper.CreateParam(item.Name, paramValue, "I"));
                }


                if (item.UniqueKey.ToMyString() == "1")
                {
                    string dataType = item.DictionaryType;
                    object ui = PageHelper.CurrentPage.FindControl("txt" + item.Name);
                    string value = "";
                    switch (dataType)
                    {
                        case "INPUT":
                        case "INPUT_NUMBER":
                        case "INPUT_INT": value = ((TextBox)ui).Text.Trim(); break;
                        case "CHOOSE": value = ((ECIChoose)ui).Code.Trim(); break;
                        case "DROPDOWNLIST": value = ((DropDownList)ui).SelectedValue.ToUpper().Trim(); break;
                    }
                    string sql = "SELECT 1 FROM " + data.Fname + "  WHERE " + item.Name + "=" + GetDBStorageFormat(item, value);

                    //2010-07-06 判断是否重复的情况 需要增加 级联条件   是否需要是否启用 再考虑 现在全启用
                    if (data.Condition.Length > 0)
                    {
                        sql += " AND " + data.Condition + "=" + cmn.SQLQ(PageHelper.Request(data.Condition));
                    }

                    if (cmn.CheckEOF(DBHelper.GetDataView(sql))) throw new Exception(item.MainAlias + ":" + value + Lang.A00075.Read());//已经存在
                }
            }

            string key = System.Guid.NewGuid().ToString();
            if (data.PrimaryKey.PrimaryKeyAutoType == 1)
            {
                //2010-06-22 修改生成主键的方法
                string primaryCreator = data.PrimaryKey.PrimaryCreator;
                if (primaryCreator.Length == 0) primaryCreator = data.Fname;
                string[] array = primaryCreator.Split(',');
                if (array.Length == 1)
                {
                    key = NoHelper.GetTableKey(primaryCreator, ts);
                }
                else
                {
                    key = DynamicNo.GetNo(data.PrimaryKey.PrimaryCreator, ts);
                }
                //2010-06-26 再次修改主键的生成方法：支持年月日等的系统数据
                //配置如下  AIOPNO,AI{YYYY},6
            }

            string sqlInsert = "INSERT INTO " + data.Fname + "(" + data.PrimaryKey.Name + "{0})";
            string sqlInsertField = "";
            string sqlValue = " VALUES(" + cmn.SQLQ(key) + "{0})";

            int rowCount = data.ListEdit.Count;


            for (int i = 0; i < rowCount; i++)
            {
                EciField field = data.ListEdit[i];

                //2010-07-01 增加配置是否需要保存的字段
                if (field.NotSave == "Y") continue;

                //如果是 修改 型 系统字段 则新增时跳过
                if (field.SystemData.ToMyString() != "" && field.SystemDataTrigger.ToMyString().ToLower() == "update") continue;
                //2010-06-22
                if (field.SystemDataTrigger.ToMyString().ToLower() == "update") continue;


                //2010-06-25
                if (field.DictionaryType == "EMPTY") continue;

                sqlInsertField += "," + field.Name;
            }

            string sqlValueField = SaveDynamicEditData(pageTable, data, DynamicEditMode.Insert, ts);

            if (!string.IsNullOrEmpty(data.Condition))
            {
                //1.可能存在画面上配置了 级联条件的显示 故存在了
                //2.可能存在不显示的情况
                if (!sqlInsertField.Contains(data.Condition))
                {
                    sqlInsertField += "," + data.Condition;
                    sqlValueField += "," + cmn.SQLQ(PageHelper.Request(data.Condition));
                }
            }

            sqlInsert = string.Format(sqlInsert, sqlInsertField);
            sqlValue = string.Format(sqlValue, sqlValueField);

            string result = sqlInsert + sqlValue;

            if (listParam.Count > 0)
            {
                //DBHelper.ExecuteNoneQuery(result, listParam.ToArray());
                TDAIClient.BusinessDB.Execute(result, true, ts, CommandType.Text, listParam.ToArray());
            }
            else
            {
                TDAIClient.BusinessDB.Execute(result, true, ts);
            }

            return key;
        }

        public static void UpdateDynamicData(Table pageTable, EciTable data, string key)
        {
            try
            {
                object ts = (PageHelper.CurrentPage as IRecord).GetTransaction();
                //唯一键检查
                List<object> listParam = new List<object>();
                try
                {

                    foreach (EciField item in data.ListEdit)
                    {

                        if (item.PhysicalType == "CLOB")
                        {

                            IElement element = ElementFactory.Create(item.DictionaryType);
                            ElementParameter param = new ElementParameter();
                            param.Table = pageTable;
                            param.Field = item;
                            param.editMode = DynamicEditMode.Update;
                            element.Init(param);
                            string paramValue = element.GetRealValue();
                            listParam.Add(DBHelper.CreateParam(item.Name, paramValue, "I"));
                        }

                        if (item.UniqueKey.ToMyString() == "1")
                        {
                            string dataType = item.DictionaryType;
                            object ui = PageHelper.CurrentPage.FindControl("txt" + item.Name);
                            string value = "";
                            switch (dataType)
                            {
                                case "INPUT":
                                case "INPUT_NUMBER":
                                case "INPUT_INT": value = ((TextBox)ui).Text.ToUpper().Trim(); break;
                                case "CHOOSE": value = ((ECIChoose)ui).Code.ToUpper().Trim(); break;
                                case "DROPDOWNLIST": value = ((DropDownList)ui).SelectedValue.ToUpper().Trim(); break;
                            }
                            string sql = "SELECT " + data.PrimaryKey.Name + " FROM " + data.Fname + "  WHERE " + item.Name + "=" + GetDBStorageFormat(item, value);
                            //2010-07-06 判断是否重复的情况 需要增加 级联条件   是否需要是否启用 再考虑 现在全启用
                            if (data.Condition.Length > 0)
                            {
                                sql += " AND " + data.Condition + "=" + cmn.SQLQ(PageHelper.Request(data.Condition));
                            }
                            DataView dv = DBHelper.GetDataView(sql);
                            if (cmn.CheckEOF(dv))
                            {
                                if (dv[0][0].ToString() != key)
                                {
                                    throw new Exception(item.MainAlias + ":" + value + Lang.A00075.Read());//已经存在
                                }
                            }
                        }
                    }
                }
                catch (Exception exUnionCheck)
                {
                    if (PlatformInfo.DevelopMode)
                    {
                        LOG.Write(exUnionCheck.Message + "  " + exUnionCheck.StackTrace, "编辑:唯一性检查");
                    }
                    throw exUnionCheck;
                }

                string sqlUpdate = "UPDATE " + data.Fname + " SET {0} WHERE " + data.PrimaryKey.Name + "=" + cmn.SQLQ(key);


                string sqlValueField = SaveDynamicEditData(pageTable, data, DynamicEditMode.Update, ts);

                if (sqlValueField.Length == 0)
                    return;
                //throw new Exception("配置错误:没有配置任何编辑的数据项");

                sqlValueField = sqlValueField.Substring(1);
                //TODO:容易出现BUG的地方
                string result = string.Format(sqlUpdate, sqlValueField);

                if (PlatformInfo.DevelopMode)
                {
                    LOG.Write(result, "UpdateDynamicData");
                }

                if (listParam.Count > 0)
                {
                    //DBHelper.ExecuteNoneQuery(result, listParam.ToArray());
                    TDAIClient.BusinessDB.Execute(result, true, ts, CommandType.Text, listParam.ToArray());
                }
                else
                {
                    TDAIClient.BusinessDB.Execute(result, true, ts);
                }
            }
            catch (Exception ex)
            {
                if (PlatformInfo.DevelopMode)
                {
                    LOG.Write(ex.Message + "  " + ex.StackTrace, "UpdateDynamicData");
                }

                throw ex;
            }
        }

        private static string SaveDynamicEditData(Table pageTable, EciTable data, DynamicEditMode editMode, object ts)
        {
            int rowCount = data.ListEdit.Count;
            string sqlValueField = "";

            if (rowCount == 0) throw new Exception(Lang.A00076.Read());//没有配置修改字段

            try
            {
                #region
                for (int i = 0; i < rowCount; i++)
                {
                    TableRow tableRow = new TableRow();
                    EciField field = data.ListEdit[i];

                    //2010-7-01 增加字段是否需要保存的设置 
                    if (field.NotSave == "Y") continue;

                    string dataType = field.DictionaryType.ToString().ToUpper();//类型
                    string name = field.Name.ToString().ToUpper();//字段名称

                    string primaryCreator = field.PrimaryCreator;
                    string value = "";
                    if (editMode == DynamicEditMode.Insert && primaryCreator.Length > 0)
                    {
                        string[] array = primaryCreator.Split(',');
                        if (array.Length == 1)
                        {
                            value = NoHelper.GetTableKey(primaryCreator, ts);
                        }
                        else
                        {
                            value = DynamicNo.GetNo(primaryCreator, ts);
                        }

                        sqlValueField += ",'" + value + "'";

                        continue;
                    }

                    #region 不需要保存的元素


                    //如果是 新增 型 系统字段 则修改时跳过
                    if (editMode == DynamicEditMode.Update && field.SystemData.ToMyString() != "" && field.SystemDataTrigger.ToMyString().ToLower() == "insert") continue;

                    //如果是 修改 型 系统字段 则新增时跳过
                    if (editMode == DynamicEditMode.Insert && field.SystemData.ToMyString() != "" && field.SystemDataTrigger.ToMyString().ToLower() == "update") continue;

                    //2010-06-22
                    if (editMode == DynamicEditMode.Update && field.SystemDataTrigger.ToMyString().ToLower() == "insert") continue;
                    if (editMode == DynamicEditMode.Insert && field.SystemDataTrigger.ToMyString().ToLower() == "update") continue;
                    if (field.DictionaryType == "EMPTY") continue;
                    #endregion

                    //规定系统数据 只能配置成文本框，但是也不正确 查询怎么办

                    IElement element = ElementFactory.Create(dataType);
                    ElementParameter param = new ElementParameter();
                    param.Table = pageTable;
                    param.Field = field;
                    param.editMode = editMode;
                    element.Init(param);


                    if (field.PhysicalType == "CLOB")
                    {
                        if (editMode == DynamicEditMode.Update)
                        {
                            sqlValueField += "," + field.Name + "= :" + field.Name;
                        }
                        else
                        {
                            sqlValueField += ",:" + field.Name;
                        }
                    }
                    else
                    {
                        sqlValueField += element.GetValue();
                    }


                }
                #endregion
            }
            catch (Exception ex)
            {
                if (PlatformInfo.DevelopMode)
                {
                    LOG.Write(ex.Message + "  " + ex.StackTrace, "SaveDynamicEditData");
                }

                throw ex;
            }

            return sqlValueField;
        }

        //---------------------------------------------------------------
        public static void UpdateDynamicDataBatch(Table pageTable, EciTable data, string key)
        {
            //唯一键检查--就不改出现唯一性检查
            string sqlUpdate = "UPDATE " + data.Fname + " SET {0} WHERE " + data.PrimaryKey.Name + "=" + cmn.SQLQ(key);
            string sqlValueField = SaveDynamicEditDataBatch(pageTable, data);
            if (sqlValueField == "") throw new Exception(Lang.A00077.Read());//没有选择要修改的内容
            sqlValueField = sqlValueField.Substring(1);

            string result = string.Format(sqlUpdate, sqlValueField);

            DBHelper.ExecuteNoneQuery(result);
        }

        public static string SaveDynamicEditDataBatch(Table pageTable, EciTable data)
        {
            DynamicEditMode editMode = DynamicEditMode.BatchUpdate;
            int rowCount = data.ListBatchEdit.Count;
            string sqlValueField = "";

            if (rowCount == 0) throw new Exception(Lang.A00076.Read());//没有配置修改字段

            #region
            for (int i = 0; i < rowCount; i++)
            {
                TableRow tableRow = new TableRow();
                EciField field = data.ListBatchEdit[i];

                string dataType = field.DictionaryType.ToString().ToUpper();//类型
                string name = field.Name.ToString().ToUpper();//字段名称

                IElement element = ElementFactory.Create(dataType);
                ElementParameter param = new ElementParameter();
                param.Table = pageTable;
                param.Field = field;
                param.editMode = editMode;
                element.Init(param);
                sqlValueField += element.GetValue();

            }
            #endregion

            return sqlValueField;
        }

        //---------------------------------------------------------------

        private static void CreateDateForQuery(TableRow tableRow, EciField field, string cellWidth, string lblWidth, string type, string editMode)
        {
            TableCell tableCell = new TableCell();
            tableCell.VerticalAlign = VerticalAlign.Top;
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Style["width"] = cellWidth;
            TextBox txtBox = new TextBox();
            txtBox.Attributes.Add("sql", field.SqlAttribute.ToLower().Replace("startend", "start"));
            txtBox.Attributes.Add("mainalias", field.MainAlias);
            txtBox.Attributes.Add("maxlength", "20");

            txtBox.Style["width"] = "85%";
            txtBox.ID = "txt" + field.Name;
            txtBox.CssClass = "Wdate";
            string TypeConfig = field.DictionaryTypeConfig;
            TypeConfig = "";
            if (TypeConfig == "")
            {
                TypeConfig = "yyyy-MM-dd";
            }
            txtBox.Attributes.Add("onfocus", "WdatePicker({dateFmt:'" + TypeConfig + "'})");
            txtBox.AutoCompleteType = AutoCompleteType.Disabled;

            tableCell.Controls.Add(txtBox);//新增文本框控件
            tableRow.Cells.Add(tableCell);

            if (field.SqlAttribute.ToLower().Contains("startend"))
            {
                tableCell = new TableCell();
                tableCell.Attributes.Add("style", "white-space:nowrap");
                tableCell.Attributes.Add("class", "lbl");
                tableCell.Attributes.Add("width", lblWidth);
                Label label = new Label();
                label.Text = Lang.A00078.Read();//至;
                tableCell.Controls.Add(label);
                tableRow.Cells.Add(tableCell);


                tableCell = new TableCell();
                tableCell.Attributes.Add("style", "white-space:nowrap");
                tableCell.Attributes.Add("width", cellWidth);
                txtBox = new TextBox();
                txtBox.Attributes.Add("sql", field.SqlAttribute.ToLower().Replace("startend", "end"));
                txtBox.Attributes.Add("mainalias", field.MainAlias);
                txtBox.Attributes.Add("maxlength", "20");

                txtBox.Style["width"] = "85%";
                txtBox.ID = "txt" + field.Name + "end";
                txtBox.CssClass = "Wdate";
                txtBox.Attributes.Add("onfocus", "WdatePicker({dateFmt:'" + TypeConfig + "'})");
                txtBox.AutoCompleteType = AutoCompleteType.Disabled;
                tableCell.Controls.Add(txtBox);//新增文本框控件

                if (field.SqlAttribute.ToLower().Contains("null"))
                {
                    CheckBox chkNull = new CheckBox();
                    chkNull.ID = "txt" + field.Name + "end" + "chkNull";
                    tableCell.Controls.Add(chkNull);
                    chkNull.Attributes.Add("sql", field.Name + "|checkbox|isnull");
                    string script = "QueryIsNull('" + chkNull.ID + "','" + "txt" + field.Name + ",txt" + field.Name + "end" + "');";
                    chkNull.Attributes.Add("onclick", script);


                    HtmlGenericControl body = PageHelper.CurrentPage.FindControl("myBody") as HtmlGenericControl;

                    string onload = body.Attributes["onload"].ToMyString();
                    if (!onload.Contains(script))
                    {
                        body.Attributes["onload"] = onload + script;
                    }
                }
                tableRow.Cells.Add(tableCell);
            }
        }

        private static void CreateRadionButtonList(TableRow tableRow, EciField field, DataRow dataRow, string query, string cellWidth, string type, string editMode)
        {
            // Y|分拨,N|自提
            TableCell tableCell = new TableCell();
            tableCell.Attributes.Add("style", "white-space:nowrap");
            tableCell.Style["width"] = cellWidth;

            if (string.IsNullOrEmpty(field.DropdownlistConfig)) throw new Exception(Lang.A00079.Read());//没有维护字典配置

            DataTable table = new DataTable();
            table.Columns.Add("CODE");
            table.Columns.Add("NAME");
            string[] array = field.DropdownlistConfig.Split(',');
            foreach (string item in array)
            {
                string[] itemArray = item.Split('|');
                string code = itemArray[0].Trim();
                string name = "";
                if (itemArray.Length == 0)
                {
                    name = code;
                }
                else
                {
                    name = itemArray[1].Trim();
                }

                table.Rows.Add(new object[] { code, name });
            }

            RadioButtonList rbl = new RadioButtonList();
            rbl.RepeatDirection = RepeatDirection.Horizontal;

            rbl.CssClass = "GridRadion";
            rbl.CellPadding = 0;
            rbl.CellSpacing = 0;



            foreach (DataRow item in table.Rows)
            {
                rbl.Items.Add(new ListItem(item["NAME"].ToString(), item["CODE"].ToString()));
            }


            rbl.Attributes.Add("sql", field.SqlAttribute);
            rbl.Attributes.Add("mainalias", field.MainAlias);

            rbl.ID = "txt" + field.Name;


            tableCell.Controls.Add(rbl);

            tableRow.Cells.Add(tableCell);


            if (dataRow != null)
            {
                foreach (ListItem list in rbl.Items)
                {
                    if (list.Value == dataRow[field.Name].ToString()) list.Selected = true;
                }
            }
            else
            {
                rbl.Items[0].Selected = true;
            }
        }

        public static string GetDynamicSQL(EciField field, string value, DynamicEditMode editMode)
        {
            string sql = ",";
            if (editMode == DynamicEditMode.Update)
            {
                sql += field.Name + "=";
            }

            if (string.IsNullOrEmpty(value))
            {
                sql += "NULL";
            }
            else
            {
                sql += GetDBStorageFormat(field, value);
            }

            return sql;
        }

        public static string GetDBStorageFormat(EciField field, string value)
        {
            string sql = "";

            try
            {
                switch (field.PhysicalType)
                {
                    case "VARCHAR2":
                    case "CHAR": CheckDataLength(field, value); sql += cmn.SQLQ(value); break;
                    case "NUMBER":
                    case "FLOAT": sql += value.Trim() == "" ? "NULL" : cmn.SQLQ(double.Parse(value)); break;
                    case "DATE": CheckDateFormat(field, value); sql += cmn.SQLQ(DateTime.Parse(value)); break;
                    default: throw new Exception(Lang.A00080.Read() + field.Name + "-" + field.MainAlias + Lang.A00232.Read());//没有配置 数据库存储类型
                }
            }
            catch (Exception ex)
            {
                if (PlatformInfo.DevelopMode)
                {
                    LOG.Write(ex.Message + " " + ex.StackTrace, "GetDBStorageFormat");
                }
                throw ex;
            }
            return sql;
        }

        private static void CheckDataLength(EciField field, string value)
        {
            if (field.FieldLength.ToIntIgnoreError() > 0)
            {
                if (value.ByteLength() > (field.FieldLength.ToIntIgnoreError())) throw new Exception(field.MainAlias + Lang.A00233.Read() + field.FieldLength + Lang.A00234.Read() + value.ByteLength());//当前长度
            }
        }



        private static void CheckDateFormat(EciField field, string value)
        {
            if (value.Trim().Length > 0)
            {
                DateTime date = DateTime.Now;
                if (!DateTime.TryParse(value, out  date))
                {
                    throw new Exception(field.MainAlias + Lang.A00042.Read());//" 维护的日期格式不正确"
                }
            }
        }

        public static string GetSumSQL(EciTable table)
        {
            string sql = "SELECT {0} FROM " + table.Fname + " A  WHERE 1=1";

            if (table.IsMultiCompany.ToMyString() == "1") sql += " AND COMPANY_CODE=" + cmn.SQLQ(UserInfo.CompanyCode);

            if (!string.IsNullOrEmpty(table.DefaultCondition)) sql += " AND " + table.DefaultCondition;

            if (!string.IsNullOrEmpty(table.Condition))
            {
                string condition = PageHelper.Request(table.Condition);
                sql += " AND " + table.Condition + "=" + cmn.SQLQ(condition);
            }

            string query = "";

            foreach (EciField field in table.ListSum)
            {
                query += ",SUM(" + "A." + field.Name + ") AS " + field.Name;
            }

            if (query.Length > 0) query = query.Substring(1);
            if (query == "") query = "1";
            sql = string.Format(sql, query);

            return sql;
        }

        public static string GetEditExtendSQL(EciTable table)
        {
            string sql = "SELECT {0} FROM " + table.ListFieldExtend[0].JoinTable;
            string query = "";
            foreach (EciFieldExtend fieldExtend in table.ListFieldExtend)
            {
                query += "," + fieldExtend.Name;
            }

            if (query.Length > 0) query = query.Substring(1);
            if (query == "") query = "1";
            sql = string.Format(sql, query);

            if (PageHelper.Request(table.ListFieldExtend[0].JoinCondition) == "")
            {
                throw new Exception(Lang.A00081.Read() + table.ListFieldExtend[0].JoinCondition);//没有传入参数
            }

            sql += " WHERE " + table.ListFieldExtend[0].JoinTableField + "=" + PageHelper.Request(table.ListFieldExtend[0].JoinCondition);

            return sql;
        }

        public static string RequestParameter(EciTable table)
        {
            string url = "";
            if (!string.IsNullOrEmpty(table.Condition))
            {
                url += "&" + table.Condition + "=" + PageHelper.Request(table.Condition);
            }

            string param = table.Param;
            string[] array = param.Split(',');
            foreach (string item in array)
            {
                if (item.Trim() == "") continue;
                if (url.Contains(item)) continue;
                url += "&" + item + "=" + PageHelper.Request(item);
            }

            return url;
        }

        public static void ReturnParameterToPageSession()
        {
            //TODO:收集系统关键字 ReturnParameter
            string url = "";
            string parameter = PageHelper.Request("ReturnParameter");
            if (!string.IsNullOrEmpty(parameter))
            {
                string[] array = parameter.Split(',');
                foreach (string key in array)
                {
                    if (string.IsNullOrEmpty(key)) continue;
                    url += "&" + key + "=" + PageHelper.Request(key);
                }

                string pageId = PageHelper.CurrentPage.Page.ClientID;
                if (PageHelper.Request("tablename") != "") pageId += "_" + PageHelper.Request("tablename");
                PageHelper.CurrentPage.Session[pageId + "_ReturnParameter"] = url;
            }
        }

        public static string ReturnParameter(string url)
        {
            //移动到CMN中
            string pageId = PageHelper.CurrentPage.Page.ClientID;
            if (PageHelper.Request("tablename") != "") pageId += "_" + PageHelper.Request("tablename");

            if (PageHelper.CurrentPage.Session[pageId + "_ReturnParameter"] == null)
            {
                return url;
            }
            else
            {
                return url + PageHelper.CurrentPage.Session[pageId + "_ReturnParameter"].ToString();
            }
        }

        public static bool EditHideForSystemField(EciField field)
        {
            return field.SystemData.ToString() != "" && field.SystemDataShowon == 0;
        }
    }
}